Multistream-select
This crate implements the multistream-select
protocol, which is the protocol used by libp2p
to negotiate which protocol to use with the remote.
Note: This crate is used by the internals of libp2p, and it is not required to understand it in order to use libp2p.
Whenever a new connection or a new multiplexed substream is opened, libp2p uses
multistream-select
to negotiate with the remote which protocol to use. After a protocol has
been successfully negotiated, the stream (i.e. the connection or the multiplexed substream)
immediately stops using multistream-select
and starts using the negotiated protocol.
Protocol explanation
The dialer has two options available: either request the list of protocols that the listener supports, or suggest a protocol. If a protocol is suggested, the listener can either accept (by answering with the same protocol name) or refuse the choice (by answering "not available").
Examples
For a dialer:
# fn main() {
use bytes::Bytes;
use multistream_select::dialer_select_proto;
use futures::{Future, Sink, Stream};
use tokio_tcp::TcpStream;
use tokio::runtime::current_thread::Runtime;
#[derive(Debug, Copy, Clone)]
enum MyProto { Echo, Hello }
let client = TcpStream::connect(&"127.0.0.1:10333".parse().unwrap())
.from_err()
.and_then(move |connec| {
let protos = vec![b"/echo/1.0.0", b"/echo/2.5.0"];
dialer_select_proto(connec, protos).map(|r| r.0)
});
let mut rt = Runtime::new().unwrap();
let negotiated_protocol = rt.block_on(client).expect("failed to find a protocol");
println!("negotiated: {:?}", negotiated_protocol);
# }